<template>
  <!-- 关键：移除 v-if="showFlag"，否则组件不会初始化 -->
  <el-dialog
      title="物料产品选择"
      :visible.sync="showFlag"
      :modal="false"
      width="60%"
      center
      append-to-body
  >
    <!-- 主内容区域 -->
    <div class="dialog-content">
      <el-row :gutter="20" style="height: 100%; display: flex;">
        <!-- 左侧分类树 -->
        <el-col :span="4" :xs="24" class="tree-col">
          <div class="head-container">
            <el-input
                v-model="itemTypeName"
                placeholder="请输入分类名称"
                clearable
                size="small"
                prefix-icon="el-icon-search"
                style="margin-bottom: 20px"
            />
          </div>
          <div class="tree-container">
            <el-tree
                :data="itemTypeOptions"
                :props="defaultProps"
                :expand-on-click-node="false"
                :filter-node-method="filterNode"
                ref="tree"
                default-expand-all
                @node-click="handleNodeClick"
            />
          </div>
        </el-col>

        <!-- 右侧物料列表 -->
        <el-col :span="20" :xs="24" class="item-list-container">
          <!-- 搜索开关
          <el-row style="margin-bottom: 10px;">
            <el-button size="mini" @click="showSearch = !showSearch">
              {{ showSearch ? '收起搜索' : '展开搜索' }}
            </el-button>
          </el-row>
          -->
          <!-- 查询表单 -->
          <el-form
              :model="queryParams"
              ref="queryForm"
              size="small"
              :inline="true"
              v-show="showSearch"
              label-width="68px"
          >
            <el-form-item label="物料编码" prop="itemCode">
              <el-input
                  v-model="queryParams.itemCode"
                  placeholder="请输入物料编码"
                  clearable
                  style="width: 240px"
                  @keyup.enter.native="handleQuery"
              />
            </el-form-item>
            <el-form-item label="物料名称" prop="itemName">
              <el-input
                  v-model="queryParams.itemName"
                  placeholder="请输入物料名称"
                  clearable
                  style="width: 240px"
                  @keyup.enter.native="handleQuery"
              />
            </el-form-item>
            <el-form-item>
              <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
              <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
            </el-form-item>
          </el-form>

          <!-- 滚动表格区域 -->
          <div class="table-scroll-container">
            <el-table
                v-loading="loading"
                :data="itemList"
                @current-change="handleCurrent"
                @row-dblclick="handleRowDbClick"
                style="width: 100%;"
            >
              <el-table-column width="50" align="center">
                <template v-slot="scope">
                  <el-radio
                      v-model="selectedItemId"
                      :label="scope.row.itemId"
                      @change="handleRowChange(scope.row)"
                  ></el-radio>
                </template>
              </el-table-column>
              <el-table-column label="物料编码" width="120" align="center" key="itemCode" prop="itemCode" v-if="columns[0].visible" />
              <el-table-column label="物料名称" min-width="120" align="left" key="itemName" prop="itemName" v-if="columns[1].visible" :show-overflow-tooltip="true" />
              <el-table-column label="物料图片" align="left" prop="imgUrl">
                <template slot-scope="scope">
                  <image-preview
                      v-if="scope.row.imgUrl"
                      :src="scope.row.imgUrl"
                      :width="50"
                      :height="50"
                  />
                </template>
              </el-table-column>
              <el-table-column label="规格型号" align="left" key="specification" prop="specification" v-if="columns[2].visible" :show-overflow-tooltip="true" />
              <el-table-column label="单位" align="center" key="unitOfMeasure" prop="unitOfMeasure" v-if="columns[3].visible" :show-overflow-tooltip="true" />
              <el-table-column label="物料/产品" align="center" key="itemOrProduct" prop="itemOrProduct" v-if="columns[4].visible" :show-overflow-tooltip="true">
                <template slot-scope="scope">
                  <dict-tag :options="dict.type.mes_item_product" :value="scope.row.itemOrProduct" />
                </template>
              </el-table-column>
              <el-table-column label="所属分类" align="center" key="itemTypeName" prop="itemTypeName" v-if="columns[5].visible" width="120" />
              <el-table-column label="创建时间" align="center" prop="createTime" v-if="columns[6].visible" width="160">
                <template slot-scope="scope">
                  <span>{{ parseTime(scope.row.createTime) }}</span>
                </template>
              </el-table-column>
            </el-table>
          </div>

          <!-- 分页 -->
          <div class="pagination-footer">
            <pagination
                v-show="total > 0"
                :total="total"
                :page.sync="queryParams.pageNum"
                :limit.sync="queryParams.pageSize"
                @pagination="getList"
            />
          </div>
        </el-col>
      </el-row>
    </div>

    <!-- 底部按钮 -->
    <div slot="footer" class="dialog-footer">
      <el-button type="primary" @click="confirmSelect">确 定</el-button>
      <el-button @click="showFlag = false">取 消</el-button>
    </div>
  </el-dialog>
</template>

<script>
import { listMdItem } from "@/api/mes/md/mdItem";
import { treeselect } from "@/api/mes/md/itemtype";
import Treeselect from "@riophae/vue-treeselect";
import "@riophae/vue-treeselect/dist/vue-treeselect.css";
import { parseTime } from "@/utils";

export default {
  name: "MdItemSingle",
  dicts: ['mes_item_product'],
  components: { Treeselect },
  data() {
    return {
      // 核心：允许父组件通过 this.$refs.itemSelect.showFlag = true 控制
      showFlag: false,
      selectedItemId: undefined,
      selectedRows: undefined,
      total: 0,
      itemList: null,
      itemTypeName: undefined,
      itemTypeOptions: undefined,
      defaultProps: {
        children: "children",
        label: "label"
      },
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        itemCode: undefined,
        itemName: undefined,
        itemTypeId: 0
      },
      columns: [
        { key: 0, label: `物料/产品编码`, visible: true },
        { key: 1, label: `物料/产品名称`, visible: true },
        { key: 2, label: `规格型号`, visible: true },
        { key: 3, label: `单位`, visible: true },
        { key: 4, label: `物料/产品`, visible: true },
        { key: 5, label: `物料分类`, visible: true },
        { key: 6, label: `创建时间`, visible: true }
      ],
      loading: false,
      showSearch: true // ✅ 确保查询表单显示
    };
  },
  watch: {
    // ✅ 监听 showFlag 变为 true 时加载数据
    showFlag: {
      handler(newVal) {
        if (newVal) {
          this.getList(); // 弹窗打开时加载数据
        }
      },
      immediate: false
    },
    itemTypeName(val) {
      this.$refs.tree.filter(val);
    }
  },
  created() {
    // 初始化分类树
    this.getTreeselect();
  },
  methods: {
    getList() {
      this.loading = true;
      listMdItem(this.queryParams).then(response => {
        this.itemList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    getTreeselect() {
      treeselect().then(response => {
        this.itemTypeOptions = response.data;
      });
    },
    filterNode(value, data) {
      if (!value) return true;
      return data.label.indexOf(value) !== -1;
    },
    handleNodeClick(data) {
      this.queryParams.itemTypeId = data.id;
      this.handleQuery();
    },
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    handleCurrent(row) {
      if (row) {
        this.selectedRows = row;
      }
    },
    handleRowDbClick(row) {
      if (row) {
        this.selectedRows = row;
        this.$emit('onSelected', this.selectedRows);
        this.showFlag = false;
      }
    },
    handleRowChange(row) {
      if (row) {
        this.selectedRows = row;
      }
    },
    confirmSelect() {
      if (!this.selectedRows) {
        this.$notify({
          title: '提示',
          type: 'warning',
          message: '请至少选择一条数据!'
        });
        return;
      }
      this.$emit('onSelected', this.selectedRows);
      this.showFlag = false;
    }
  }
};
</script>

<style scoped>
/* 保持原有样式不变 */
.dialog-content {
  height: calc(80vh - 120px);
  display: flex;
  flex-direction: column;
  overflow: hidden;
}

.tree-col {
  display: flex;
  flex-direction: column;
  height: 100%;
}

.head-container {
  padding: 0 10px;
}

.tree-container {
  flex: 1;
  overflow-y: auto;
  border: 1px solid #ebeef5;
  border-radius: 4px;
  margin-top: 10px;
}

.item-list-container {
  display: flex;
  flex-direction: column;
  height: 100%;
  min-height: 0;
}

.table-scroll-container {
  flex: 1;
  overflow-y: auto;
  border: 1px solid #ebeef5;
  border-radius: 4px;
  margin-bottom: 10px;
}

.table-scroll-container ::v-deep .el-table__body-wrapper {
  height: 100%;
}

.pagination-footer {
  flex-shrink: 0;
  padding: 10px 0;
  background-color: #fff;
}

.pagination-footer >>> .el-pagination {
  display: flex;
  align-items: center;
  white-space: nowrap;
}

.pagination-footer >>> .el-pagination .el-input--mini {
  width: 50px;
}

.pagination-footer >>> .el-pagination__jump {
  margin-left: 10px;
}
</style>
